import { Request, Response } from "express";
import { query } from "../config/database";
import { Role, CreateRoleRequest } from "../model/types";
import {
  successResponse,
  errorResponse,
  paginatedResponse,
} from "../utils/response";

export class RoleController {
  // 获取角色列表
  static async getRoles(req: Request, res: Response): Promise<void> {
    try {
      const {
        page = 1,
        pageSize = 20,
        name,
        sortBy = "createdAt",
        sortOrder = "desc",
      } = req.query;

      const offset = (Number(page) - 1) * Number(pageSize);
      let whereConditions = [];
      let params: any[] = [];

      // 构建WHERE条件
      if (name) {
        whereConditions.push("name LIKE ?");
        params.push(`%${name}%`);
      }

      const whereClause =
        whereConditions.length > 0
          ? `WHERE ${whereConditions.join(" AND ")}`
          : "";

      // 获取总数
      const countQuery = `SELECT COUNT(*) as total FROM roles ${whereClause}`;
      const { rows: countRows } = await query(countQuery, params);
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / Number(pageSize));

      // 获取角色列表
      const roleQuery = `
        SELECT
          id,
          name,
          description,
          permissions,
          created_at as createdAt
        FROM roles
        ${whereClause}
        ORDER BY ${sortBy} ${sortOrder}
        LIMIT ? OFFSET ?
      `;

      params.push(Number(pageSize), offset);
      const { rows } = await query(roleQuery, params);

      // 处理权限数据
      const roles = rows.map((role: any) => ({
        ...role,
        permissions: role.permissions ? JSON.parse(role.permissions) : [],
      }));

      paginatedResponse(res, roles, {
        page: Number(page),
        pageSize: Number(pageSize),
        total,
        totalPages,
      });
    } catch (error) {
      console.error("获取角色列表失败:", error);
      errorResponse(res, "获取角色列表失败");
    }
  }

  // 根据ID获取角色
  static async getRoleById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      const { rows } = await query(
        `
        SELECT
          id,
          name,
          description,
          permissions,
          created_at as createdAt
        FROM roles
        WHERE id = ?
      `,
        [id]
      );

      if (rows.length === 0) {
        return errorResponse(res, "角色不存在", 404);
      }

      const role = {
        ...rows[0],
        permissions: rows[0].permissions ? JSON.parse(rows[0].permissions) : [],
      };

      successResponse(res, role);
    } catch (error) {
      console.error("获取角色详情失败:", error);
      errorResponse(res, "获取角色详情失败");
    }
  }

  // 创建角色
  static async createRole(req: Request, res: Response): Promise<void> {
    try {
      const {
        name,
        description,
        permissions = [],
      }: CreateRoleRequest = req.body;

      // 验证必填字段
      if (!name) {
        return errorResponse(res, "角色名称不能为空");
      }

      // 检查角色名是否已存在
      const { rows: existingRoles } = await query(
        "SELECT id FROM roles WHERE name = ?",
        [name]
      );

      if (existingRoles.length > 0) {
        return errorResponse(res, "角色名称已存在");
      }

      // 创建角色
      const insertQuery = `
        INSERT INTO roles (name, description, permissions)
        VALUES (?, ?, ?)
      `;

      const { rows } = await query(insertQuery, [
        name,
        description || null,
        JSON.stringify(permissions),
      ]);

      successResponse(res, { id: rows[0].insertId }, "角色创建成功", 201);
    } catch (error) {
      console.error("创建角色失败:", error);
      errorResponse(res, "创建角色失败");
    }
  }

  // 更新角色
  static async updateRole(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const { name, description, permissions }: Partial<CreateRoleRequest> =
        req.body;

      // 检查角色是否存在
      const { rows: existingRoles } = await query(
        "SELECT id FROM roles WHERE id = ?",
        [id]
      );

      if (existingRoles.length === 0) {
        return errorResponse(res, "角色不存在", 404);
      }

      // 检查角色名是否已被其他角色使用
      if (name) {
        const { rows: nameCheck } = await query(
          "SELECT id FROM roles WHERE name = ? AND id != ?",
          [name, id]
        );

        if (nameCheck.length > 0) {
          return errorResponse(res, "角色名称已存在");
        }
      }

      // 更新角色
      const updateFields = [];
      const params = [];

      if (name !== undefined) {
        updateFields.push("name = ?");
        params.push(name);
      }

      if (description !== undefined) {
        updateFields.push("description = ?");
        params.push(description);
      }

      if (permissions !== undefined) {
        updateFields.push("permissions = ?");
        params.push(JSON.stringify(permissions));
      }

      if (updateFields.length > 0) {
        const updateQuery = `UPDATE roles SET ${updateFields.join(
          ", "
        )} WHERE id = ?`;
        params.push(id);
        await query(updateQuery, params);
      }

      successResponse(res, null, "角色更新成功");
    } catch (error) {
      console.error("更新角色失败:", error);
      errorResponse(res, "更新角色失败");
    }
  }

  // 删除角色
  static async deleteRole(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      // 检查角色是否存在
      const { rows: existingRoles } = await query(
        "SELECT id FROM roles WHERE id = ?",
        [id]
      );

      if (existingRoles.length === 0) {
        return errorResponse(res, "角色不存在", 404);
      }

      // 检查是否为系统角色（这里假设超级管理员角色不能删除）
      if (existingRoles[0].name === "超级管理员") {
        return errorResponse(res, "系统角色不能删除");
      }

      // 检查是否有用户正在使用此角色
      const { rows: userRoles } = await query(
        "SELECT COUNT(*) as count FROM user_roles WHERE role_id = ?",
        [id]
      );

      if (userRoles[0].count > 0) {
        return errorResponse(res, "该角色正在被用户使用，无法删除");
      }

      // 删除用户角色关联（虽然前面检查了，但为了安全）
      await query("DELETE FROM user_roles WHERE role_id = ?", [id]);

      // 删除角色
      await query("DELETE FROM roles WHERE id = ?", [id]);

      successResponse(res, null, "角色删除成功");
    } catch (error) {
      console.error("删除角色失败:", error);
      errorResponse(res, "删除角色失败");
    }
  }

  // 更新角色权限
  static async updateRolePermissions(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      const { id } = req.params;
      const { permissions } = req.body;

      if (!Array.isArray(permissions)) {
        return errorResponse(res, "权限格式不正确");
      }

      // 检查角色是否存在
      const { rows: existingRoles } = await query(
        "SELECT id FROM roles WHERE id = ?",
        [id]
      );

      if (existingRoles.length === 0) {
        return errorResponse(res, "角色不存在", 404);
      }

      // 更新权限
      await query("UPDATE roles SET permissions = ? WHERE id = ?", [
        JSON.stringify(permissions),
        id,
      ]);

      successResponse(res, null, "角色权限更新成功");
    } catch (error) {
      console.error("更新角色权限失败:", error);
      errorResponse(res, "更新角色权限失败");
    }
  }

  // 获取所有权限列表（用于前端构建权限树）
  static async getAllPermissions(req: Request, res: Response): Promise<void> {
    try {
      const allPermissions = [
        {
          id: "user",
          label: "用户管理",
          children: [
            { id: "user:view", label: "查看用户" },
            { id: "user:create", label: "创建用户" },
            { id: "user:edit", label: "编辑用户" },
            { id: "user:delete", label: "删除用户" },
          ],
        },
        {
          id: "role",
          label: "角色管理",
          children: [
            { id: "role:view", label: "查看角色" },
            { id: "role:create", label: "创建角色" },
            { id: "role:edit", label: "编辑角色" },
            { id: "role:delete", label: "删除角色" },
            { id: "role:permission", label: "权限管理" },
          ],
        },
        {
          id: "knowledge",
          label: "知识管理",
          children: [
            { id: "knowledge:category:view", label: "查看分类" },
            { id: "knowledge:category:manage", label: "管理分类" },
            { id: "knowledge:article:view", label: "查看文章" },
            { id: "knowledge:article:manage", label: "管理文章" },
            { id: "knowledge:video:view", label: "查看视频" },
            { id: "knowledge:video:manage", label: "管理视频" },
            { id: "knowledge:question:view", label: "查看题库" },
            { id: "knowledge:question:manage", label: "管理题库" },
          ],
        },
        {
          id: "event",
          label: "事件管理",
          children: [
            { id: "event:type:view", label: "查看事件类型" },
            { id: "event:type:manage", label: "管理事件类型" },
            { id: "event:record:view", label: "查看事件记录" },
            { id: "event:record:manage", label: "管理事件记录" },
          ],
        },
        {
          id: "volunteer",
          label: "志愿者管理",
          children: [
            { id: "volunteer:application:view", label: "查看申请" },
            { id: "volunteer:application:review", label: "审核申请" },
            { id: "volunteer:info:view", label: "查看信息" },
            { id: "volunteer:info:manage", label: "管理信息" },
            { id: "volunteer:skill:manage", label: "技能管理" },
          ],
        },
        {
          id: "notification",
          label: "通知管理",
          children: [
            { id: "notification:send", label: "发送通知" },
            { id: "notification:history", label: "查看历史" },
          ],
        },
        {
          id: "file",
          label: "文件管理",
          children: [
            { id: "file:upload", label: "上传文件" },
            { id: "file:view", label: "查看文件" },
            { id: "file:delete", label: "删除文件" },
          ],
        },
        {
          id: "system",
          label: "系统设置",
          children: [
            { id: "system:setting", label: "系统设置" },
            { id: "system:statistics", label: "查看统计" },
          ],
        },
      ];

      successResponse(res, allPermissions, "获取权限列表成功");
    } catch (error) {
      console.error("获取权限列表失败:", error);
      errorResponse(res, "获取权限列表失败");
    }
  }
}
